package com.linzp.bishe.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.linzp.bishe.service.SaveExcelData;

import java.util.List;

/**
 * @ClassName AchievementTransformationExcelListener
 * @Description 描述
 * @Author LinZePeng
 * @Date 2022/2/27 20:39
 * @Version 1.0
 */
public class AchievementTransformationExcelListener implements ReadListener<AchievementTransformationExcel> {
	/**
	 * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
	 */
	private static final int BATCH_COUNT = 100;
	/**
	 * 缓存的数据
	 */
	private List<AchievementTransformationExcel> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);


	private SaveExcelData saveExcelData;

	public AchievementTransformationExcelListener(SaveExcelData demoDAO) {
		this.saveExcelData = demoDAO;
	}
	/**
	 * 这个每一条数据解析都会来调用
	 *
	 * @param excel
	 * @param analysisContext
	 */
	@Override
	public void invoke(AchievementTransformationExcel excel, AnalysisContext analysisContext) {
			cachedDataList.add(excel);
			// 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
			if (cachedDataList.size() >= BATCH_COUNT) {
				saveData();
				// 存储完成清理 list
				cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
			}
	}
	/**
	 * 所有数据解析完成了 都会来调用
	 * @Param [analysisContext]
	 * @return void
	 */
	@Override
	public void doAfterAllAnalysed(AnalysisContext analysisContext) {
		saveData();
	}

	/**
	 * 加上存储数据库
	 */
	private void saveData() {
		if(cachedDataList.size()>0) {
			saveExcelData.saveAchievementTransformationExcel(cachedDataList);
		}
	}
}
